#include "IOServicePool.h"

IOServicePool::~IOServicePool()
{
	std::cout << "~IOServicePool()" << std::endl;
}

void IOServicePool::stop()
{
	for (auto& work : _works) {
		work.reset();
	}
	for (auto& t : _threads) {
		t.join();
	}
}

boost::asio::io_context& IOServicePool::getIOC()
{
	auto& ioc = _iocs[_nextIoc++];
	if (_nextIoc == _iocs.size()) {
		_nextIoc = 0;
	}
	
	return ioc;
}

IOServicePool& IOServicePool::GetInst()
{
	static IOServicePool instance(1);
	return instance;
}

IOServicePool::IOServicePool(size_t size) :_iocs(size),_works(size),_nextIoc(0){
	//for (size_t i = 0;i < size;++i) {
	//	_works.emplace_back(std::make_unique<work_guard>(boost::asio::make_work_guard(_iocs[i])));
	//}
	//for (size_t i = 0;i < size;++i) {
	//	_threads.emplace_back([this, &i]() {
	//		_iocs[i].run();
	//		});
	//}
	for (auto& ioc : _iocs) {
		_works.emplace_back(std::make_unique<work_guard>(boost::asio::make_work_guard(ioc)));
	}

	for (auto& ioc : _iocs) {
		/*	_threads.emplace_back(std::thread([this, &ioc]() {
				ioc.run();
				}));*/
		_threads.emplace_back([&ioc]() {
			ioc.run();
			});
	}
}